package com.example.iread.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.iread.MainActivity;
import com.example.iread.R;
import com.example.iread.application.MyApplication;
import com.example.iread.bean.ResponseBean;
import com.example.iread.bean.UserBean;
import com.example.iread.dao.UserDao;
import com.example.iread.exception.MyException;
import com.example.iread.http.UserApi;
import com.example.iread.util.WindowUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_login_username, et_login_password;

    private final String TAG = "SoRiya";

    UserDao userDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        WindowUtil.setTransparentStatusBar(getWindow());

        userDao = MyApplication.getInstance().getDb().userDao();

        et_login_username = findViewById(R.id.et_login_username);
        et_login_password = findViewById(R.id.et_login_password);

        View btn_login = findViewById(R.id.btn_login);

        btn_login.setOnClickListener(this);

        TextView tv_sign_up = findViewById(R.id.tv_sign_up);
        tv_sign_up.setOnClickListener(v -> {
            Intent intent = new Intent(this, RegisterActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        });

    }

    @Override
    public void onClick(View view) {
        String username = et_login_username.getText().toString();
        String password = et_login_password.getText().toString();

        if ("".equals(username) || "".equals(password)) {
            Toast.makeText(this, "请正确输入", Toast.LENGTH_SHORT).show();
            return;
        }

        Map<String, String> body = new HashMap<>();
        body.put("username", username);
        body.put("password", password);
        UserApi.login(body, this::loginHandler);
    }

    @SuppressLint("CommitPrefEdits")
    public void loginHandler(ResponseBean res) {
        try {
            JSONObject resJson = new JSONObject(res.data.toString());

            int userId = resJson.getInt("id");
            String username = resJson.getString("username");
            String token = resJson.getString("token");

            SharedPreferences sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putInt("userId", userId);
            edit.putString("username", username);
            edit.putString("token", token);
            edit.apply();

            UserApi.getUserInfo(userInfoRes -> {
                try {
                    JSONObject data = new JSONObject(
                            new GsonBuilder().serializeNulls().create().toJson(userInfoRes.data)
                    );

                    UserBean userBean = new Gson().fromJson(data.toString(), UserBean.class);

                    userDao.clear();
                    userDao.insert(userBean);
                } catch (JSONException e) {
                    e.printStackTrace();
                    throw new MyException(500, e.getMessage());
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
            throw new MyException(500, e.getMessage());
        }
        Intent intent = new Intent();
        intent.setClass(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}